package search.lucene;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.util.Version;

/**
 *
 * @author cosmin
 */
public class Query extends Abstract {

    /**
     * Static instance used for singleton
     */
    protected static Query _instance = null;

    /**
     * Singleton method
     *
     * @return One single instance
     */
    public static Query getInstance() {
        if (null == Query._instance) {
            Query._instance = new Query();
        }
        return Query._instance;
    }

    public Query() {
        super();
    }

    public boolean doSearch(String text) {
        boolean hasResult = true;
        try {
            org.apache.lucene.search.Query q = new QueryParser(Version.LUCENE_40, "content", this._analyzer).parse(QueryParser.escape(text));
            SortField sortField = new SortField("dateReal", SortField.Type.LONG, true);
            Sort sortFiltre = new Sort(sortField);
            TopFieldDocs topFieldDocs = this._indexSearcher.search(q, null, this.hitsPerPage, sortFiltre);
            this.hits = topFieldDocs.scoreDocs;
            this.totalHits = topFieldDocs.totalHits;
            this.hasResults = true;
        } catch (IOException | ParseException ex) {
            hasResult = false;
            Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex);
        }
        return hasResult;
    }
}
